<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <div>
      <el-form
        :model="userForm"
        :rules="userRules"
        ref="userRef"
        label-width="100px"
      >
        <el-form-item label="登录名称" prop="username">
          <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="userForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default {
  name: "UserInfo",
  data() {
    return {
      // 表单数据对象
      userForm: {
        username: "",
        nickname: "",
        email: ""
      },
      // 表单验证规则对象
      userRules: {
        nickname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          {
            pattern: /^\S{1,10}$/,
            message: "用户名必须由1-10位非空字符",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { type: "email", message: "请输入用户邮箱", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    // **组件初始化时，从 store 下的 userInfo 中，获取表单默认展示数据**
    // this.userForm.username = this.$store.state.userInfo.username
    // this.userForm.nickname = this.$store.state.userInfo.nickname
    // this.userForm.email = this.$store.state.userInfo.email
    // 对象赋值，不能直接赋值，避免双向改变数据，进行浅拷贝
    this.userForm = Object.assign({}, this.$store.state.userInfo)
  },
  watch: {
    // 监听数据变化，重新进行赋，值如：页面刷新
    "$store.state.userInfo"() {
      this.userForm = Object.assign({}, this.$store.state.userInfo)
    }
  },
  methods: {
    // 重置表单
    reset() {
      // 使用el-form表单的方法，进行重置
      this.$ref.userRef.resetFields()
      //  恢复表单默认展示
      this.userForm = Object.assign({}, this.$store.state.userInfo)
    },
    // 提交修改
    updateUserInfo() {
      this.$refs.userRef.validate(async (valid) => {
        // 不通过，停止
        if (!valid) return
        // 通过。发起请求
        const { data: res } = await this.$http.put(
          "/my/userinfo",
          this.userForm
        )
        console.log(res)
        if (res.code === 0) {
          // 提示用户
          this.$message.success(res.message)
          // 重新获取用户信息
          this.$store.dispatch("getUserInfo")
        } else {
          // 提交失败，提示
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>